﻿using System;
using System.Globalization;

namespace MetaSharp.Transformation
{
    public class SourceSpan : IEquatable<SourceSpan>
    {
        public long Start { get; private set; }
        public long End { get; private set; }

        private SourceSpan(long start, long end)
        {
            this.Start = start;
            this.End = end;
        }

        public SourceSpan(IStream start, IStream end)
        {
            this.Start = start.Index;
            this.End = end.Index;
        }

        public static SourceSpan From(long start, long end)
        {
            return new SourceSpan(start, end);
        }

        public static SourceSpan operator +(SourceSpan left, SourceSpan right)
        {
            if (object.ReferenceEquals(left, null))
                return right;
            if (object.ReferenceEquals(right, null))
                return left;

            var start = left.Start < right.Start
                ? left.Start
                : right.Start;
            var end = left.End > right.End
                ? left.End
                : right.End;

            return new SourceSpan(start, end);
        }

        public static bool operator !=(SourceSpan left, SourceSpan right)
        {
            return !SourceSpan.Equals(left, right);
        }

        public static bool operator ==(SourceSpan left, SourceSpan right)
        {
            return SourceSpan.Equals(left, right);
        }

        private static bool Equals(SourceSpan left, SourceSpan right)
        {
            var l = object.ReferenceEquals(left, null);
            var r = object.ReferenceEquals(right, null);
            if (l && r)
                return true;
            if (l || r)
                return false;

            return left.Start == right.Start && left.End == right.End;
        }

        public override bool Equals(object obj)
        {
            var other = obj as SourceSpan;
            if (other == null)
                return false;

            return SourceSpan.Equals(this, other);
        }

        public bool Equals(SourceSpan other)
        {
            return SourceSpan.Equals(this, other);
        }

        public override int GetHashCode()
        {
            return base.GetHashCode();
        }


        public override string ToString()
        {
            return string.Format(
                CultureInfo.InvariantCulture,
                "{{{0},{1}}}",
                this.Start,
                this.End);
        }
    }
}
